﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PServiceBus.Core.Runtime {
    public class EndpointUri {
        public string Username { get; set; }
        public string Password { get; set; }
        public string Host { get; set; }
        public string LocalizedHost {
            get {
                return Host.Replace("*", "localhost");
            }
        }
        public int Port { get; set; }
        public string Path { get; set; }

        static Regex _endpointRegex = new Regex(@"(?:endpoint://)(?:(?<UserName>[^:]*)?(?:\:)?(?<Password>[^:@]*)?(?:@))?(?<Host>[^:]*)(?:\:)?(?<Port>\d*)(?:\/)?(?<Path>[^/]*)",
            RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static Regex _oldRegexp = new Regex(@"(?<Host>[^:]+)(?:\:)?(?<Port>\d+);UserID=(?<UserName>[^=;]+)?(?:;)?Password=(?<Password>[^;]+)?(?:;Queue=)?(?<Path>[^;]+)?(?:;)?",
             RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);


        /// <summary>
        /// Parse custom endpoint uri
        /// e.x. endpoint://username:password@localhost:9900/test
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public static EndpointUri Parse(string uri) {
            var match = _endpointRegex.Match(uri);
            if (!match.Success) match = _oldRegexp.Match(uri);
            return new EndpointUri() {
                Host = match.Groups["Host"].Value,
                Port = Int32.Parse(match.Groups["Port"].Value),
                Username = match.Groups["UserName"].Value,
                Password = match.Groups["Password"].Value,
                Path = match.Groups["Path"].Value
            };
        }
    }
}
